// pages/publicmusic/publicmusic.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    audioCtx: null, // 存储audio上下文

    musicPercent: 0, // 进度条百分比
    duration: 0, // 歌曲总时长
    currentTime: 0, // 当前播放时间
    musicList: [],
  },

  // 播放
  onPlay: function (e) {
    this.data.audioCtx.play()
    // 修改播放状态
    const detailmusic = this.data.musicList.find(item => item.id === e.target.dataset.id)
    detailmusic.isplay = true
    const list = this.data.musicList.map((item) => {
      if (item.id === e.target.dataset.id){
        item = {...detailmusic}
      }
      return item
    })
    console.log(list);
    this.setData({
      musicList: list
    })
    // 监听音乐进度条变化
    this.data.audioCtx.onTimeUpdate(() => {
      this.updateProgress()
    })
    // 监听音乐播放结束
    this.data.audioCtx.onEnded(() => {
      this.setData({
        musicPercent: 0
      })
    })
  },
  // 暂停
  onPause: function(e) {
    this.data.audioCtx.pause()
     // 修改播放状态
     const detailmusic = this.data.musicList.find(item => item.id === e.target.dataset.id)
    detailmusic.isplay = false
    const list = this.data.musicList.map((item) => {
      if (item.id === e.target.dataset.id){
        item = {...detailmusic}
      }
      return item
    })
    console.log(list);
    this.setData({
      musicList: list
    })
  },

  updateProgress: function () {
    const currentTime = this.data.audioCtx.currentTime
    const duration = this.data.audioCtx.duration 
    this.setData({
      musicPercent: currentTime/duration*100,
      currentTime: this.formdate(Math.ceil(currentTime)),
      duration: this.formdate(Math.ceil(duration))
    })
  },
  formdate: function (seconds) {
    const minute = Math.floor(seconds/60)
    const second = seconds%60
    if(minute < 10 && second < 10) {
      return `0${minute}:0${second}`
    }else if(minute < 10 && second >= 10) {
      return `0${minute}:${second}`
    }else if (minute >= 10 && second < 10){
      return `${minute}:0${second}`
    }else {
      return `${minute}:${second}`
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    const audioCtx = wx.createInnerAudioContext()
    audioCtx.src = "/audio/有点甜.m4a"
    this.setData({
      audioCtx,
    })
  },
  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

    this.setData({
      currentTime: this.data.audioCtx.currentTime, 
      duration: this.data.audioCtx.duration
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.data.audioCtx.destroy()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})